package org.cllib.tool;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.LinkedHashMap;

public class PropertyManager {
	public String separator = "=";
	java.util.Map<String , String> map = new LinkedHashMap<String, String>();
	public String encoding = "GBK";
	
	
	public void load(File f) throws Exception{
		BufferedReader br = null;
		
		try {
			br = new BufferedReader(new InputStreamReader(new FileInputStream(f) , encoding));
			String line = null;
			
			while((line = br.readLine()) != null){
				String[] values = line.split("=");
				if(values != null && values.length == 2){
					String key = values[0];
					String value = values[1];
					map.put(key, value);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if(br != null){
				try {
					br.close();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}	
			}
						
		}
	}
	
	public void save(File f) throws Exception{
		BufferedWriter bw = null;
		try {
			bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f) , encoding));
			
			for(String key : map.keySet()){
				String value = map.get(key);
				bw.write(String.format("%s%s%s%s", key , separator , value , "\n"));
			}
			
			bw.flush();
			bw.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if(bw != null){
				try {
					bw.close();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	public String getEncoding() {
		return encoding;
	}

	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

	public String getValue(String key){
		return getValue(key , null);
	}
	
	public String getValue(String key , String defaultValue){
		String value = map.get(key);
		if(value == null){
			value = defaultValue;
		}
		
		return value;
	}
	
	public void setValue(String key , String value){
		map.put(key, value);
	}
	
	public String[] getKeys(){
		return map.keySet().toArray(new String[0]);
	}
	
	public String[] getValues(){
		return map.values().toArray(new String[0]);
	}
	
}
